#+_+ coding:utf-8 +_+

import time
from config import Config
import log
import hashlib
import xml.etree.ElementTree as ET
from enum import MSG_TYPE
from message import *

logger = log.Log("/tmp/log/mp_wechar","mpproxy")
logger.closeDebug()


def Deal(reqData):
    "nimei"

def parseXML(reqData):
    try:
        rootTag = ET.fromstring(reqData)
    except:
        rootTag = None
    try:
        msgType = rootTag.find("MsgType").text
    except:
        msgType = None
    
    return rootTag,msgType


def DealClientMessage(reqData):
    """ Deal Message from client wechat client passed by wechat server 
        @param reqData: post data in xml format
        @return : message passed to client 
    """
    
    rootTag,msgType = parseXML(reqData)
    if None==  rootTag or None ==  msgType:
        logger.err("Parse XML error")
        return None
        
    if msgType == MSG_TYPE.TEXT :
        msg = TextMsg()
    else :
        logger.err("Unknown message type")
        return None
    msg.Init(rootTag)
    return msg.Deal()



def DealWXSniff(reqData):
    if CheckSignature(reqData):
        return str(reqData["echostr"])
    else :
        logger.err("Not wechat request")
        return str(None)

def CheckSignature(reqData):
    try:
        signature = str(reqData["signature"])
        timestamp = str(reqData["timestamp"])
        nonce     = str(reqData["nonce"])
        token     = Config["token"]
    except Exception as e:
        logger.err("signature error")
        return False
    sha1Obj = hashlib.sha1()
    sha1Obj.update(''.join(sorted([timestamp,nonce,token])))
    _signature = sha1Obj.hexdigest()
    if _signature == signature:
        return True
    return False
            
    
